/*
 * @Description: 支付相关API
 */

import { _ToAsyncAwait } from '@gykeji/jsutil';
import { HandleApiError } from "../utils";

/**
 * @Description: 发起支付请求
 * @param {string} orderId - 订单ID
 * @param {number} amount - 支付金额
 * @param {string} productName - 产品名称
 * @return {Promise} 返回支付URL或错误信息
 */
const ApiPostOrderPay = ({orderId, amount, productName}) => _ToAsyncAwait(
    new Promise((resolve, reject) => {   //异步
        uni.request({
            url: "https://4601f58c0c21.ngrok-free.app/alipay/pay",
            method: 'POST',
            data: {
                orderId,
                amount,
                productName,
                timestamp: Date.now()
            },
            success: (res) => {
                if (res.data.statusCode !== 200) {
                    reject(res.data.msg || "支付失败");
                } else {
                    resolve(res.data.data);
                }
            },
            fail: (err) => {
                reject("网络请求失败");
            }
        })
    })
);

/**
 * @Description: 支付处理函数
 * @param {Object} orderDetail - 订单详情
 * @param {string} orderName - 订单名称前缀
 * @return {Promise} 返回支付结果
 */
const handlePayApi = async (orderDetail, orderName) => {
    if (!orderDetail?.id || !orderDetail?.price) {
        return Promise.reject("订单信息不完整");
    }
    
    try {
        const { error, result } = await ApiPostOrderPay({
            orderId: orderDetail.id,
            amount: orderDetail.price,
            productName: `${orderName}${orderDetail.id}`
        });
        
        if (!HandleApiError(error)) {
            return result;
        }
    } catch (err) {
        throw err;
    }
};

export {
    ApiPostOrderPay,
    handlePayApi
}